package require tclodbc

namespace eval ::wt::database::dbManager:: {
  variable dataSources ""

  namespace export registerDataSource isDataSourceRegistered \
    openDataSource closeDataSource dbDriver

  wt::server::atEnd ::wt::database::dbManager::endRequest
}

proc ::wt::database::dbManager::registerDataSource {dataSourceId handler} {
  set ds [table create]
  table set ds id $dataSourceId
  table set ds handler $handler
  table set ds isConnected 0
  table set ds connection ""
  variable dataSources
  table set dataSources $dataSourceId $ds
}

proc ::wt::database::dbManager::isDataSourceRegistered {dataSourceId} {
  variable dataSources
  return [table has $dataSources $dataSourceId]
}

proc ::wt::database::dbManager::getDataSource {dataSourceId} {
  variable dataSources
  return [table get $dataSources $dataSourceId]
}

# Get an existing connection or create a new one

proc ::wt::database::dbManager::openDataSource {dataSourceId} {
  variable dataSources
  dbDriver openDataSource $dataSourceId
  set ds [table get $dataSources $dataSourceId]
  set conn [table get $ds connection]
  if {$conn == ""} {
    set conn [dbDriver openDataSource $dataSourceId]
    if {$conn == ""} {
      error "Failed to open data source ID \"$dataSourceId\" using data source handler \"$ns\"."
    }
    set ds [table get $dataSources $dataSourceId]
    table set ds isConnected 1
    table set ds connection $conn
    table set dataSources $dataSourceId $ds
  }
  return $conn
}

# Close the connection

proc ::wt::database::dbManager::closeDataSource {dataSourceId} {
  variable dataSources
  set ds [table get $dataSources $dataSourceId]
  if {[table get $ds isConnected]} {
    dbDriver closeDataSource $dataSourceId
    set ds [table get $dataSources $dataSourceId]
    table set ds isConnected 0
    table set ds connection ""
    table set dataSources $dataSourceId $ds
  }
}

proc ::wt::database::dbManager::setDataSourceConnection {dataSourceId conn} {
  variable dataSources
  closeDataSource $dataSourceId
  if {$conn != ""} {
    set ds [table get $dataSources $dataSourceId]
    table set ds isConnected 1
    table set ds connection $conn
    table set dataSources $dataSourceId $ds
  }
}

proc ::wt::database::dbManager::dbDriver {command dataSourceId {args {}}} {
  variable dataSources
  if {![table has $dataSources $dataSourceId]} {
    error "Unknown data source ID \"$dataSourceId\"."
  }
  set ds [table get $dataSources $dataSourceId]
  set ns [table get $ds handler]
  return [eval {::wt::util::callVirtualProc} [list $ns] [list $command] {ds} $args]
}

proc ::wt::database::dbManager::endRequest {} {
  variable dataSources
  foreach key [table keys $dataSources] {
    closeDataSource $key
  }
}

package provide wt::database::dbManager 1
